package com.lx.controller;

import com.lx.util.FileEncoderUtil;
import com.lx.util.MinIoUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.PhantomReference;
import java.net.URLEncoder;

/**
 * 雒鑫
 */
@RestController
public class UserController {
    @Resource
    private MinIoUtil minIoUtil;

    /**
     * 文件上传测试
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
        minIoUtil.upload(file);
        return ResponseEntity.ok("成功");
    }

    /**
     * 文件下载测试
     *
     * @param fileName
     * @param response
     * @throws IOException
     */
    @GetMapping("/download")
    public void downloadFile(@RequestParam String fileName, HttpServletResponse response) throws IOException {
        try (InputStream inputStream = minIoUtil.downloadFile(fileName)) {
            // 文件名进行编码
            FileEncoderUtil.FileEncoder(fileName, response);

            // 获取响应输出流
            ServletOutputStream outputStream = response.getOutputStream();

            // 文件内容写入响应输出流
            byte[] buffer = new byte[1024];

            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            //刷新以下文件输出流
            outputStream.flush();

        } catch (Exception e) {
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write("下载失败");
        }

    }
}
